//
//  TranslationViewController.swift
//  ScarnKing
//
//  Created by ninebot on 2025/7/22.
//

import UIKit
import SVProgressHUD

class TranslationViewController: UIViewController {
    
    // MARK: - UI Components
    private let headerView = UIView()
    private let titleLabel = UILabel()
    private let backButton = UIButton(type: .system)
    
    private let scrollView = UIScrollView()
    private let contentView = UIView()
    
    // 输入区域
    private let inputContainer = UIView()
    private let inputLabel = UILabel()
    private let inputTextView = UITextView()
    private let inputPlaceholderLabel = UILabel()
    private let clearInputButton = UIButton(type: .system)
    private let inputCountLabel = UILabel()
    
    // 语言选择区域
    private let languageContainer = UIView()
    private let fromLanguageButton = UIButton(type: .system)
    private let swapButton = UIButton(type: .system)
    private let toLanguageButton = UIButton(type: .system)
    
    // 翻译按钮
    private let translateButton = UIButton(type: .system)
    
    // 结果区域
    private let resultContainer = UIView()
    private let resultLabel = UILabel()
    private let resultTextView = UITextView()
    private let copyButton = UIButton(type: .system)
    private let shareButton = UIButton(type: .system)
    private let resultCountLabel = UILabel()
    
    // MARK: - Data
    private var selectedFromLanguage = Language.auto
    private var selectedToLanguage = Language.english
    private var preloadText: String?
    
    // MARK: - Network
    private let networkManager = SKAFNetWork()
    
    // MARK: - Languages
    private let languages: [Language] = [
        .auto, .chinese, .english, .japanese, .korean, .french, .german, .spanish, .italian, .portuguese, .russian
    ]
    
    // MARK: - Lifecycle
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        setupConstraints()
        setupKeyboardHandling()
        
        if let preloadText = preloadText {
            inputTextView.text = preloadText
            inputPlaceholderLabel.isHidden = true
            clearInputButton.isHidden = false
            updateInputCount()
            updateTranslateButtonState()
        }
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        updateTranslationTheme()
        // 隐藏系统导航栏和底部tab栏
        navigationController?.setNavigationBarHidden(true, animated: false)
        tabBarController?.tabBar.isHidden = true
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        // 显示系统导航栏和底部tab栏
        navigationController?.setNavigationBarHidden(false, animated: false)
        tabBarController?.tabBar.isHidden = false
    }
    
    // MARK: - UI Setup
    private func setupUI() {
        let isDark = ThemeManager.shared.isDarkMode
        view.backgroundColor = ThemeManager.Colors.background(for: isDark)
        
        setupHeaderView()
        setupInputContainer()
        setupLanguageContainer()
        setupTranslateButton()
        setupResultContainer()
        
        // 监听主题变化
        NotificationCenter.default.addObserver(self, selector: #selector(themeDidChange), name: .themeDidChange, object: nil)
    }
    
    private func setupHeaderView() {
        let isDark = ThemeManager.shared.isDarkMode
        
        titleLabel.text = "AI翻译"
        titleLabel.font = UIFont.systemFont(ofSize: 18, weight: .semibold)
        titleLabel.textColor = ThemeManager.Colors.text(for: isDark)
        titleLabel.textAlignment = .center
        
        backButton.setImage(UIImage(systemName: "chevron.left"), for: .normal)
        backButton.tintColor = ThemeManager.Colors.text(for: isDark)
        backButton.addTarget(self, action: #selector(backButtonTapped), for: .touchUpInside)
        
        headerView.backgroundColor = .clear
    }
    
    private func setupInputContainer() {
        let isDark = ThemeManager.shared.isDarkMode
        
        inputContainer.backgroundColor = ThemeManager.Colors.cardBackground(for: isDark)
        inputContainer.layer.cornerRadius = 12
        inputContainer.layer.shadowColor = UIColor.black.cgColor
        inputContainer.layer.shadowOpacity = 0.1
        inputContainer.layer.shadowOffset = CGSize(width: 0, height: 2)
        inputContainer.layer.shadowRadius = 4
        
        inputLabel.text = "输入文本"
        inputLabel.font = UIFont.systemFont(ofSize: 16, weight: .medium)
        inputLabel.textColor = ThemeManager.Colors.text(for: isDark)
        
        inputTextView.font = UIFont.systemFont(ofSize: 16)
        inputTextView.textColor = ThemeManager.Colors.text(for: isDark)
        inputTextView.backgroundColor = .clear
        inputTextView.delegate = self
        inputTextView.isScrollEnabled = true
        inputTextView.showsVerticalScrollIndicator = false
        
        inputPlaceholderLabel.text = "请输入要翻译的文本..."
        inputPlaceholderLabel.font = UIFont.systemFont(ofSize: 16)
        inputPlaceholderLabel.textColor = ThemeManager.Colors.secondaryText(for: isDark)
        inputPlaceholderLabel.numberOfLines = 0
        
        clearInputButton.setImage(UIImage(systemName: "xmark.circle.fill"), for: .normal)
        clearInputButton.tintColor = ThemeManager.Colors.secondaryText(for: isDark)
        clearInputButton.addTarget(self, action: #selector(clearInputTapped), for: .touchUpInside)
        clearInputButton.isHidden = true
        
        inputCountLabel.font = UIFont.systemFont(ofSize: 12)
        inputCountLabel.textColor = ThemeManager.Colors.secondaryText(for: isDark)
        inputCountLabel.textAlignment = .right
        inputCountLabel.text = "0/5000"
    }
    
    private func setupLanguageContainer() {
        let isDark = ThemeManager.shared.isDarkMode
        
        languageContainer.backgroundColor = ThemeManager.Colors.cardBackground(for: isDark)
        languageContainer.layer.cornerRadius = 12
        languageContainer.layer.shadowColor = UIColor.black.cgColor
        languageContainer.layer.shadowOpacity = 0.1
        languageContainer.layer.shadowOffset = CGSize(width: 0, height: 2)
        languageContainer.layer.shadowRadius = 4
        
        // 源语言按钮
        fromLanguageButton.setTitle(selectedFromLanguage.nativeName, for: .normal)
        fromLanguageButton.setTitleColor(ThemeManager.Colors.text(for: isDark), for: .normal)
        fromLanguageButton.titleLabel?.font = UIFont.systemFont(ofSize: 16, weight: .medium)
        fromLanguageButton.backgroundColor = ThemeManager.Colors.background(for: isDark)
        fromLanguageButton.layer.cornerRadius = 8
        fromLanguageButton.layer.borderWidth = 1
        fromLanguageButton.layer.borderColor = ThemeManager.Colors.border(for: isDark).cgColor
        fromLanguageButton.addTarget(self, action: #selector(fromLanguageTapped), for: .touchUpInside)
        
        // 交换按钮
        swapButton.setImage(UIImage(systemName: "arrow.left.arrow.right"), for: .normal)
        swapButton.tintColor = UIColor.systemBlue
        swapButton.backgroundColor = UIColor.systemBlue.withAlphaComponent(0.1)
        swapButton.layer.cornerRadius = 20
        swapButton.addTarget(self, action: #selector(swapLanguages), for: .touchUpInside)
        
        // 目标语言按钮
        toLanguageButton.setTitle(selectedToLanguage.nativeName, for: .normal)
        toLanguageButton.setTitleColor(ThemeManager.Colors.text(for: isDark), for: .normal)
        toLanguageButton.titleLabel?.font = UIFont.systemFont(ofSize: 16, weight: .medium)
        toLanguageButton.backgroundColor = ThemeManager.Colors.background(for: isDark)
        toLanguageButton.layer.cornerRadius = 8
        toLanguageButton.layer.borderWidth = 1
        toLanguageButton.layer.borderColor = ThemeManager.Colors.border(for: isDark).cgColor
        toLanguageButton.addTarget(self, action: #selector(toLanguageTapped), for: .touchUpInside)
    }
    
    private func setupTranslateButton() {
        let isDark = ThemeManager.shared.isDarkMode
        
        translateButton.setTitle("开始翻译", for: .normal)
        translateButton.setTitleColor(.white, for: .normal)
        translateButton.titleLabel?.font = UIFont.systemFont(ofSize: 18, weight: .semibold)
        translateButton.backgroundColor = UIColor.systemBlue
        translateButton.layer.cornerRadius = 12
        translateButton.addTarget(self, action: #selector(translateTapped), for: .touchUpInside)
        translateButton.isEnabled = false
        translateButton.alpha = 0.6
    }
    
    private func setupResultContainer() {
        let isDark = ThemeManager.shared.isDarkMode
        
        resultContainer.backgroundColor = ThemeManager.Colors.cardBackground(for: isDark)
        resultContainer.layer.cornerRadius = 12
        resultContainer.layer.shadowColor = UIColor.black.cgColor
        resultContainer.layer.shadowOpacity = 0.1
        resultContainer.layer.shadowOffset = CGSize(width: 0, height: 2)
        resultContainer.layer.shadowRadius = 4
        resultContainer.isHidden = true
        
        resultLabel.text = "翻译结果"
        resultLabel.font = UIFont.systemFont(ofSize: 16, weight: .medium)
        resultLabel.textColor = ThemeManager.Colors.text(for: isDark)
        
        resultTextView.font = UIFont.systemFont(ofSize: 16)
        resultTextView.textColor = ThemeManager.Colors.text(for: isDark)
        resultTextView.backgroundColor = .clear
        resultTextView.isEditable = false
        resultTextView.isScrollEnabled = true
        resultTextView.showsVerticalScrollIndicator = false
        
        copyButton.setImage(UIImage(systemName: "doc.on.doc"), for: .normal)
        copyButton.tintColor = UIColor.systemBlue
        copyButton.addTarget(self, action: #selector(copyResultTapped), for: .touchUpInside)
        
        shareButton.setImage(UIImage(systemName: "square.and.arrow.up"), for: .normal)
        shareButton.tintColor = UIColor.systemBlue
        shareButton.addTarget(self, action: #selector(shareResultTapped), for: .touchUpInside)
        
        resultCountLabel.font = UIFont.systemFont(ofSize: 12)
        resultCountLabel.textColor = ThemeManager.Colors.secondaryText(for: isDark)
        resultCountLabel.textAlignment = .right
        resultCountLabel.text = "0字符"
    }
    
    // MARK: - Constraints
    private func setupConstraints() {
        // 设置translatesAutoresizingMaskIntoConstraints
        [headerView, titleLabel, backButton, scrollView, contentView, 
         inputContainer, inputLabel, inputTextView, inputPlaceholderLabel, clearInputButton, inputCountLabel,
         languageContainer, fromLanguageButton, swapButton, toLanguageButton,
         translateButton, resultContainer, resultLabel, resultTextView, copyButton, shareButton, resultCountLabel].forEach {
            $0.translatesAutoresizingMaskIntoConstraints = false
        }
        
        // 添加子视图
        headerView.addSubview(titleLabel)
        headerView.addSubview(backButton)
        view.addSubview(headerView)
        
        inputContainer.addSubview(inputLabel)
        inputContainer.addSubview(inputTextView)
        inputContainer.addSubview(inputPlaceholderLabel)
        inputContainer.addSubview(clearInputButton)
        inputContainer.addSubview(inputCountLabel)
        
        languageContainer.addSubview(fromLanguageButton)
        languageContainer.addSubview(swapButton)
        languageContainer.addSubview(toLanguageButton)
        
        resultContainer.addSubview(resultLabel)
        resultContainer.addSubview(resultTextView)
        resultContainer.addSubview(copyButton)
        resultContainer.addSubview(shareButton)
        resultContainer.addSubview(resultCountLabel)
        
        contentView.addSubview(inputContainer)
        contentView.addSubview(languageContainer)
        contentView.addSubview(translateButton)
        contentView.addSubview(resultContainer)
        
        scrollView.addSubview(contentView)
        view.addSubview(scrollView)
        
        NSLayoutConstraint.activate([
            // Header
            headerView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 10),
            headerView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20),
            headerView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -20),
            headerView.heightAnchor.constraint(equalToConstant: 44),
            
            backButton.leadingAnchor.constraint(equalTo: headerView.leadingAnchor),
            backButton.centerYAnchor.constraint(equalTo: headerView.centerYAnchor),
            backButton.widthAnchor.constraint(equalToConstant: 44),
            backButton.heightAnchor.constraint(equalToConstant: 44),
            
            titleLabel.centerXAnchor.constraint(equalTo: headerView.centerXAnchor),
            titleLabel.centerYAnchor.constraint(equalTo: headerView.centerYAnchor),
            
            // ScrollView
            scrollView.topAnchor.constraint(equalTo: headerView.bottomAnchor, constant: 20),
            scrollView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
            scrollView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
            scrollView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor),
            
            // ContentView
            contentView.topAnchor.constraint(equalTo: scrollView.topAnchor),
            contentView.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor),
            contentView.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor),
            contentView.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor),
            contentView.widthAnchor.constraint(equalTo: scrollView.widthAnchor),
            
            // Input Container
            inputContainer.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 20),
            inputContainer.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 20),
            inputContainer.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -20),
            inputContainer.heightAnchor.constraint(equalToConstant: 200),
            
            inputLabel.topAnchor.constraint(equalTo: inputContainer.topAnchor, constant: 16),
            inputLabel.leadingAnchor.constraint(equalTo: inputContainer.leadingAnchor, constant: 16),
            inputLabel.trailingAnchor.constraint(equalTo: inputContainer.trailingAnchor, constant: -16),
            
            inputTextView.topAnchor.constraint(equalTo: inputLabel.bottomAnchor, constant: 12),
            inputTextView.leadingAnchor.constraint(equalTo: inputContainer.leadingAnchor, constant: 16),
            inputTextView.trailingAnchor.constraint(equalTo: clearInputButton.leadingAnchor, constant: -8),
            inputTextView.bottomAnchor.constraint(equalTo: inputCountLabel.topAnchor, constant: -8),
            
            inputPlaceholderLabel.topAnchor.constraint(equalTo: inputTextView.topAnchor, constant: 8),
            inputPlaceholderLabel.leadingAnchor.constraint(equalTo: inputTextView.leadingAnchor, constant: 4),
            inputPlaceholderLabel.trailingAnchor.constraint(equalTo: inputTextView.trailingAnchor, constant: -4),
            
            clearInputButton.topAnchor.constraint(equalTo: inputContainer.topAnchor, constant: 16),
            clearInputButton.trailingAnchor.constraint(equalTo: inputContainer.trailingAnchor, constant: -16),
            clearInputButton.widthAnchor.constraint(equalToConstant: 24),
            clearInputButton.heightAnchor.constraint(equalToConstant: 24),
            
            inputCountLabel.bottomAnchor.constraint(equalTo: inputContainer.bottomAnchor, constant: -16),
            inputCountLabel.trailingAnchor.constraint(equalTo: inputContainer.trailingAnchor, constant: -16),
            
            // Language Container
            languageContainer.topAnchor.constraint(equalTo: inputContainer.bottomAnchor, constant: 20),
            languageContainer.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 20),
            languageContainer.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -20),
            languageContainer.heightAnchor.constraint(equalToConstant: 80),
            
            fromLanguageButton.leadingAnchor.constraint(equalTo: languageContainer.leadingAnchor, constant: 16),
            fromLanguageButton.centerYAnchor.constraint(equalTo: languageContainer.centerYAnchor),
            fromLanguageButton.widthAnchor.constraint(equalToConstant: 100),
            fromLanguageButton.heightAnchor.constraint(equalToConstant: 40),
            
            swapButton.centerXAnchor.constraint(equalTo: languageContainer.centerXAnchor),
            swapButton.centerYAnchor.constraint(equalTo: languageContainer.centerYAnchor),
            swapButton.widthAnchor.constraint(equalToConstant: 40),
            swapButton.heightAnchor.constraint(equalToConstant: 40),
            
            toLanguageButton.trailingAnchor.constraint(equalTo: languageContainer.trailingAnchor, constant: -16),
            toLanguageButton.centerYAnchor.constraint(equalTo: languageContainer.centerYAnchor),
            toLanguageButton.widthAnchor.constraint(equalToConstant: 100),
            toLanguageButton.heightAnchor.constraint(equalToConstant: 40),
            
            // Translate Button
            translateButton.topAnchor.constraint(equalTo: languageContainer.bottomAnchor, constant: 20),
            translateButton.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 20),
            translateButton.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -20),
            translateButton.heightAnchor.constraint(equalToConstant: 50),
            
            // Result Container
            resultContainer.topAnchor.constraint(equalTo: translateButton.bottomAnchor, constant: 20),
            resultContainer.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 20),
            resultContainer.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -20),
            resultContainer.heightAnchor.constraint(equalToConstant: 200),
            resultContainer.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -20),
            
            resultLabel.topAnchor.constraint(equalTo: resultContainer.topAnchor, constant: 16),
            resultLabel.leadingAnchor.constraint(equalTo: resultContainer.leadingAnchor, constant: 16),
            resultLabel.trailingAnchor.constraint(equalTo: resultContainer.trailingAnchor, constant: -16),
            
            resultTextView.topAnchor.constraint(equalTo: resultLabel.bottomAnchor, constant: 12),
            resultTextView.leadingAnchor.constraint(equalTo: resultContainer.leadingAnchor, constant: 16),
            resultTextView.trailingAnchor.constraint(equalTo: resultContainer.trailingAnchor, constant: -16),
            resultTextView.bottomAnchor.constraint(equalTo: resultCountLabel.topAnchor, constant: -8),
            
            copyButton.topAnchor.constraint(equalTo: resultContainer.topAnchor, constant: 16),
            copyButton.trailingAnchor.constraint(equalTo: shareButton.leadingAnchor, constant: -12),
            copyButton.widthAnchor.constraint(equalToConstant: 24),
            copyButton.heightAnchor.constraint(equalToConstant: 24),
            
            shareButton.topAnchor.constraint(equalTo: resultContainer.topAnchor, constant: 16),
            shareButton.trailingAnchor.constraint(equalTo: resultContainer.trailingAnchor, constant: -16),
            shareButton.widthAnchor.constraint(equalToConstant: 24),
            shareButton.heightAnchor.constraint(equalToConstant: 24),
            
            resultCountLabel.bottomAnchor.constraint(equalTo: resultContainer.bottomAnchor, constant: -16),
            resultCountLabel.trailingAnchor.constraint(equalTo: resultContainer.trailingAnchor, constant: -16)
        ])
    }
    
    // MARK: - Keyboard Handling
    private func setupKeyboardHandling() {
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil)
    }
    
    @objc private func keyboardWillShow(_ notification: Notification) {
        guard let keyboardFrame = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect else { return }
        let keyboardHeight = keyboardFrame.height
        
        scrollView.contentInset.bottom = keyboardHeight
        scrollView.verticalScrollIndicatorInsets.bottom = keyboardHeight
    }
    
    @objc private func keyboardWillHide(_ notification: Notification) {
        scrollView.contentInset.bottom = 0
        scrollView.verticalScrollIndicatorInsets.bottom = 0
    }
    
    // MARK: - Actions
    @objc private func backButtonTapped() {
        navigationController?.popViewController(animated: true)
    }
    
    @objc private func clearInputTapped() {
        inputTextView.text = ""
        inputPlaceholderLabel.isHidden = false
        clearInputButton.isHidden = true
        updateInputCount()
        updateTranslateButtonState()
        hideResultContainer()
    }
    
    @objc private func fromLanguageTapped() {
        showLanguagePicker(for: .from)
    }
    
    @objc private func toLanguageTapped() {
        showLanguagePicker(for: .to)
    }
    
    @objc private func swapLanguages() {
        let temp = selectedFromLanguage
        selectedFromLanguage = selectedToLanguage
        selectedToLanguage = temp
        
        fromLanguageButton.setTitle(selectedFromLanguage.nativeName, for: .normal)
        toLanguageButton.setTitle(selectedToLanguage.nativeName, for: .normal)
    }
    
    @objc private func translateTapped() {
        guard let text = inputTextView.text, !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {
            SVProgressHUD.showError(withStatus: "请输入要翻译的文本")
            return
        }
        
        SVProgressHUD.show(withStatus: "翻译中...")
        
        networkManager.texttransToLanage(
            text: text,
            to: selectedToLanguage.baiduCode,
            successHandler: { [weak self] response in
                DispatchQueue.main.async {
                    SVProgressHUD.dismiss()
                    self?.handleTranslationSuccess(response)
                }
            },
            errorMsgHandler: { [weak self] errorMsg in
                DispatchQueue.main.async {
                    SVProgressHUD.dismiss()
                    SVProgressHUD.showError(withStatus: "翻译失败: \(errorMsg)")
                }
            },
            networkFailHandler: { [weak self] error in
                DispatchQueue.main.async {
                    SVProgressHUD.dismiss()
                    SVProgressHUD.showError(withStatus: "网络错误: \(error.localizedDescription)")
                }
            }
        )
    }
    
    @objc private func copyResultTapped() {
        UIPasteboard.general.string = resultTextView.text
        SVProgressHUD.showSuccess(withStatus: "已复制到剪贴板")
    }
    
    @objc private func shareResultTapped() {
        guard let text = resultTextView.text, !text.isEmpty else { return }
        
        let activityVC = UIActivityViewController(activityItems: [text], applicationActivities: nil)
        present(activityVC, animated: true)
    }
    
    // MARK: - Helper Methods
    private func updateInputCount() {
        let count = inputTextView.text.count
        inputCountLabel.text = "\(count)/5000"
        
        if count > 4500 {
            inputCountLabel.textColor = .systemRed
        } else if count > 4000 {
            inputCountLabel.textColor = .systemOrange
        } else {
            let isDark = ThemeManager.shared.isDarkMode
            inputCountLabel.textColor = ThemeManager.Colors.secondaryText(for: isDark)
        }
    }
    
    private func updateResultCount() {
        let count = resultTextView.text.count
        resultCountLabel.text = "\(count)字符"
    }
    
    private func updateTranslateButtonState() {
        let hasText = !(inputTextView.text?.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty ?? true)
        translateButton.isEnabled = hasText
        translateButton.alpha = hasText ? 1.0 : 0.6
    }
    
    private func hideResultContainer() {
        resultContainer.isHidden = true
    }
    
    private func showResultContainer() {
        resultContainer.isHidden = false
    }
    
    private func handleTranslationSuccess(_ response: [String: Any]) {
        guard let result = response["result"] as? [[String: Any]],
              let firstResult = result.first,
              let dst = firstResult["dst"] as? String else {
            SVProgressHUD.showError(withStatus: "翻译结果解析失败")
            return
        }
        
        resultTextView.text = dst
        updateResultCount()
        showResultContainer()
        
        // 保存到历史记录
        HistoryRecordManager.shared.addTranslationRecord(
            originalText: inputTextView.text,
            translatedText: dst,
            fromLanguage: selectedFromLanguage.nativeName,
            toLanguage: selectedToLanguage.nativeName
        )
        
        SVProgressHUD.showSuccess(withStatus: "翻译完成")
    }
    
    private func showLanguagePicker(for type: LanguagePickerType) {
        let alert = UIAlertController(title: "选择语言", message: nil, preferredStyle: .actionSheet)
        
        for language in languages {
            let action = UIAlertAction(title: language.nativeName, style: .default) { [weak self] _ in
                if type == .from {
                    self?.selectedFromLanguage = language
                    self?.fromLanguageButton.setTitle(language.nativeName, for: .normal)
                } else {
                    self?.selectedToLanguage = language
                    self?.toLanguageButton.setTitle(language.nativeName, for: .normal)
                }
            }
            alert.addAction(action)
        }
        
        alert.addAction(UIAlertAction(title: "取消", style: .cancel))
        present(alert, animated: true)
    }
    
    private func updateTranslationTheme() {
        let isDark = ThemeManager.shared.isDarkMode
        
        view.backgroundColor = ThemeManager.Colors.background(for: isDark)
        titleLabel.textColor = ThemeManager.Colors.text(for: isDark)
        backButton.tintColor = ThemeManager.Colors.text(for: isDark)
        
        inputContainer.backgroundColor = ThemeManager.Colors.cardBackground(for: isDark)
        inputLabel.textColor = ThemeManager.Colors.text(for: isDark)
        inputTextView.textColor = ThemeManager.Colors.text(for: isDark)
        inputPlaceholderLabel.textColor = ThemeManager.Colors.secondaryText(for: isDark)
        clearInputButton.tintColor = ThemeManager.Colors.secondaryText(for: isDark)
        inputCountLabel.textColor = ThemeManager.Colors.secondaryText(for: isDark)
        
        languageContainer.backgroundColor = ThemeManager.Colors.cardBackground(for: isDark)
        fromLanguageButton.setTitleColor(ThemeManager.Colors.text(for: isDark), for: .normal)
        fromLanguageButton.backgroundColor = ThemeManager.Colors.background(for: isDark)
        fromLanguageButton.layer.borderColor = ThemeManager.Colors.border(for: isDark).cgColor
        toLanguageButton.setTitleColor(ThemeManager.Colors.text(for: isDark), for: .normal)
        toLanguageButton.backgroundColor = ThemeManager.Colors.background(for: isDark)
        toLanguageButton.layer.borderColor = ThemeManager.Colors.border(for: isDark).cgColor
        swapButton.tintColor = UIColor.systemBlue
        swapButton.backgroundColor = UIColor.systemBlue.withAlphaComponent(0.1)
        
        translateButton.backgroundColor = UIColor.systemBlue
        
        resultContainer.backgroundColor = ThemeManager.Colors.cardBackground(for: isDark)
        resultLabel.textColor = ThemeManager.Colors.text(for: isDark)
        resultTextView.textColor = ThemeManager.Colors.text(for: isDark)
        copyButton.tintColor = UIColor.systemBlue
        shareButton.tintColor = UIColor.systemBlue
        resultCountLabel.textColor = ThemeManager.Colors.secondaryText(for: isDark)
    }
    
    @objc private func themeDidChange() {
        updateTranslationTheme()
    }
}

// MARK: - UITextViewDelegate
extension TranslationViewController: UITextViewDelegate {
    func textViewDidChange(_ textView: UITextView) {
        inputPlaceholderLabel.isHidden = !textView.text.isEmpty
        clearInputButton.isHidden = textView.text.isEmpty
        updateInputCount()
        updateTranslateButtonState()
    }
    
    func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
        let newText = (textView.text as NSString).replacingCharacters(in: range, with: text)
        return newText.count <= 5000
    }
}

// MARK: - Language Picker Type
private enum LanguagePickerType {
    case from
    case to
} 